<template>
	<view class="my-4 text-base">
		<view class="text-base mb-4">推荐方案：【初选/7列选号池/过滤2】、【初选/前后区选号池/过滤3】、【优选/7列选号池/过滤2】、【优选/前后区选号池/过滤3】中奖率最佳。</view>
		<view class="text-h4 mb-2">选号参数</view>
		<view>全部总共 {{allParams.length}} 个方案。</view>
		<view class="text-h4 my-2">复盘开奖</view>
		<view class="flex items-center justify-between">
			<view class="me-1">本期：{{activeDrawInfo.lotteryDrawNum}}</view>
			<uni-easyinput v-model="activeDrawInfo.lotteryDrawResult" placeholder="本期开奖号码" />
		</view>
		<view class="flex items-center my-1">
			<view class="me-4">上期：{{prevDrawInfo.lotteryDrawNum}}</view>
			<view>{{prevDrawInfo.lotteryDrawResult}}</view>
		</view>
		<view class="flex items-center justify-between mb-2">
			<view>复盘：</view>
			<uni-data-select :localdata="historyData" @change="onChangeHistoryData"></uni-data-select>
		</view>
		<view class="flex items-center justify-between my-2">
			<view>号码排除：</view>
			<uni-easyinput v-model="blackNums" placeholder="号码以空格隔开，前后分区以逗号隔开" />
		</view>
		<view class="text-h4 my-2">数量设置</view>
		<view class="flex items-center justify-between">
			<view class="flex items-center justify-between me-2">
				<view class="me-1">每个方案</view>
				<uni-easyinput v-model="batchFormData.ticketQuantity" type="number" />
				<view class="ms-1">注</view>
			</view>
		</view>
		<view class="my-2">
			<button size="mini" type="primary" @click="batchGenerateOrders()">生成号码</button>
			<button size="mini" class="mx-1" @click="onReset()">重置</button>
		</view>
		<uni-title type="h3" title="统计汇总"></uni-title>
		<view class="lh-lg">
			<view>
				总数量：{{statInfo.totalTicketCount}}注（100%）（{{statInfo.totalBatchCount}}个 x {{statInfo.batchTicketCount}}
				注）
			</view>
			<view>
				总收入：{{statInfo.totalIncome}}元 / 总支出：{{statInfo.totalExpenses}}元 /
				<text
					:class="statInfo.netProfitMoney > 0 ? 'text-red-400' : 'text-green-600'">净利润：{{statInfo.netProfitMoney}}元</text>
			</view>
			<view>
				有中奖方案量：{{statInfo.winBatchCount}}个（{{statInfo.winBatchCountRate}}%） /
				无中奖方案量：{{statInfo.noWinBatchCount}}个（{{statInfo.noWinBatchCountRate}}%）
			</view>
			<view>
				盈利方案量：{{statInfo.profitBatchCount}}个（{{statInfo.profitBatchCountRate}}%） /
				亏损方案量：{{statInfo.lossBatchCount}}个（{{statInfo.lossBatchCountRate}}%)
			</view>
			<view>
				最高奖项：
				<text :class="statInfo.maxPrize.value > 0 ? 'text-red-400' : ''">
					{{statInfo.maxPrize.text}}，结果：{{statInfo.maxPrize.front+' + '+statInfo.maxPrize.back}}，奖金：{{statInfo.maxPrize.moneyText}}
				</text>
			</view>
			<uni-title type="h3" title="方案汇总"></uni-title>
			<view v-for="(item, idx) of batchList" :key="idx" class="text-base">
				<uni-title type="h4" :title="`#${idx+1} ${item.title}`"></uni-title>
				<view>
					总收入：{{item.totalIncome}}元 / 总支出：{{item.totalExpenses}}元
					/ <text
						:class="item.netProfitMoney > 0 ? 'text-red-400' : 'text-green-600'">净利润：{{item.netProfitMoney}}元</text>
				</view>
				<view>
					最高奖项：<text
						:class="item.maxPrize.value > 0 ? 'text-red-400' : ''">{{item.maxPrize.text}}，结果：{{item.maxPrize.front+' + '+item.maxPrize.back}}，奖金：{{item.maxPrize.moneyText}}</text>
				</view>
			</view>
			<uni-title type="h3" title="奖项汇总"></uni-title>
			<view v-for="i in 2" :key="i">
				{{statInfo['prize'+i].title}}：{{statInfo['prize'+i].totalTicketCount}}注（{{`${statInfo['prize'+i].prizeMoney}万*${statInfo['prize'+i].totalTicketCount}=${statInfo['prize'+i].totalIncome}万元`}}）
			</view>
			<template v-for="i in 9">
				<view v-if="i>2" :key="i" :class="statInfo['prize'+i].totalIncome>0 ? 'text-red-400' : ''">
					{{statInfo['prize'+i].title}}：{{statInfo['prize'+i].totalTicketCount}}注（{{`${statInfo['prize'+i].prizeMoney}*${statInfo['prize'+i].totalTicketCount}=${statInfo['prize'+i].totalIncome}元`}}）
				</view>
			</template>
		</view>
		<uni-title type="h3" title="奖项详情（按奖项高低排序）"></uni-title>
		<view class="lh-lg" v-for="i in 9" :key="i">
			<view :class="'text-base my-2 ' + (statInfo['prize'+i].totalIncome>0 ? 'text-red-400' : '')">
				{{statInfo['prize'+i].title}}（{{statInfo['prize'+i].totalBatchCount}}个，{{statInfo['prize'+i].totalTicketCount}}注）
			</view>
			<view v-for="(item2, idx2) in statInfo['prize'+i].list" :key="idx2">
				<view>
					第 {{item2.id}}
					批
					<text
						:class="item2.netProfitMoney > 0 ? 'text-red-400' : 'text-green-600'">（{{(item2.netProfitMoney > 0 ? '盈利' : '亏损') + Math.abs(item2.netProfitMoney) + '元'}}）</text>
				</view>
				<view>方案：{{item2.title}}</view>
				<view class="flex items-center lh-lg" v-for="(item3, idx3) in item2.drawList" :key="idx3">
					<view v-html="item3.text"></view>
					<view class="text-error mx-6">{{`${item3.frontCount}+${item3.backCount}`}}</view>
					<view class="text-error">{{`${item3.statusText}(${item3.moneyText})`}}</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';

	import {
		prize_info
	} from '@/config/dlt-config';
	import DltDataModel from '@/model/DltDataModel';
	import DltOrderModel from '@/model/DltOrderModel';
	import DltTplModel from '@/model/DltTplModel';
	import FsDriver from '@/model/FsDriver';

	const fsDriver = new FsDriver();
	const dltTplModel = new DltTplModel();
	const dltDataModel = new DltDataModel();
	const dltOrderModel = new DltOrderModel();
	const dataset = [...dltDataModel.getDataSource()];
	const statDrawal = dltDataModel.getDrawalStat(dataset);
	const weekdays = ['日', '一', '二', '三', '四', '五', '六'];

	const historyData = dataset.map((v, i) => {
		return {
			text: `${v.lotteryDrawNum} （${v.lotteryDrawTime.substring(5)} ${weekdays[new Date(v.lotteryDrawTime).getDay()]}）${v.lotteryDrawResult}`,
			value: i
		};
	});

	const prevDrawInfo = ref(dataset.length > 0 ? dataset[0] : {
		lotteryDrawNum: '',
		lotteryDrawResult: ''
	});

	const activeDrawInfo = ref({
		lotteryDrawNum: parseInt(prevDrawInfo.value.lotteryDrawNum) + 1,
		lotteryDrawResult: ''
	});

	const blackNums = ref('');
	const allParams = dltTplModel.getAllTplParams();

	const resetBatchFormData = {
		ticketQuantity: 10,
		batchQuantity: allParams.length,
	}
	const batchFormData = ref({
		...resetBatchFormData
	});
	const batchList = ref([]);
	const resetStatInfo = dltTplModel.getTplForStatInfo();
	const statInfo = ref(JSON.parse(JSON.stringify(resetStatInfo)));

	const onReset = function() {
		batchFormData.value = {
			...resetBatchFormData
		};
		prevDrawInfo.value = dataset.length > 0 ? dataset[0] : {
			lotteryDrawNum: '',
			lotteryDrawResult: ''
		};
		activeDrawInfo.value = {
			lotteryDrawNum: parseInt(prevDrawInfo.value.lotteryDrawNum) + 1,
			lotteryDrawResult: ''
		};
		statInfo.value = JSON.parse(JSON.stringify(resetStatInfo));
	}

	const onChangeHistoryData = function(value) {
		activeDrawInfo.value = dataset[value];
		prevDrawInfo.value = dataset[value + 1];
		blackNums.value = dltDataModel.getBlackNumsByPrevDrawResult(
			statDrawal.statConsecutiveNums, prevDrawInfo.value?.lotteryDrawResult
		).map(v => v.join(' ')).join(', ');
	}

	const getBigStat = () => {
		let dataStr = fsDriver.get('big-stat');
		if (dataStr) {
			return JSON.parse(dataStr);
		}
		let data = {
			paramRank: {},
			prizeRank: {}
		};
		allParams.forEach((param, i) => {
			param.title = dltTplModel.getParamText(param);
			data.paramRank[param.id] = {
				title: param.title,
				param,
				winCount: 0,
				prizeInfo: {
					// title: '一等奖',
					// count: 0,
				}
			}
		})
		prize_info.forEach(item => {
			if (item.value == 0) {
				return;
			}
			data.prizeRank['prize' + item.value] = {
				title: item.text,
				winCount: 0,
				paramInfo: {
					// title: '初选/7列选号池/过滤2',
					// count: 0,
				}
			}
		});
		return data;
	}

	const saveBigStat = (data) => {
		fsDriver.save('big-stat', JSON.stringify(data));
	}

	const batchGenerateOrders = () => {
		batchList.value = [];
		let ticketQuantity =
			parseInt(batchFormData.value.ticketQuantity) < 1 ? 1 : parseInt(batchFormData.value.ticketQuantity);
		allParams.forEach((param, i) => {
			batchList.value.push({
				...dltTplModel.getTplForOrderListItem({
					id: i + 1,
					title: dltTplModel.getParamText(param),
					ticketQuantity: ticketQuantity,
					param
				})
			})
		})
		let drawResult = activeDrawInfo.value?.lotteryDrawResult?.trim() || '';
		let prevDrawResult = prevDrawInfo.value?.lotteryDrawResult?.trim() || '';
		if (!drawResult.length) {
			uni.showToast({
				title: '请选择复盘的开奖号码',
				icon: 'error'
			})
			return;
		}

		let winBatchList = [],
			k = '';
		for (let i = 0; i < batchList.value.length; i++) {
			batchList.value[i].list = [];
			batchList.value[i].drawList = [];
			onChooseAuto(i, ticketQuantity);
			if (batchList.value[i].param.chooseMode == '优选') {
				batchList.value[i].list = dltOrderModel.getBetterNums7(statDrawal, batchList.value[i].list, '', prevDrawResult, blackNums.value)
			}
			// 开奖
			batchList.value[i].drawList = dltOrderModel.calcOrder(drawResult,
				batchList.value[i].list, true, prevDrawResult);
			// 统计
			batchList.value[i].totalIncome = 0;
			if (batchList.value[i].drawList.length > 0) {
				batchList.value[i].totalIncome = batchList.value[i].drawList.map(v => v.money)
					.reduce((a, b) => {
						return parseInt(a) + parseInt(b)
					});
				batchList.value[i].maxPrize = dltOrderModel.getMaxPrize(batchList.value[i].drawList);
			}
			batchList.value[i].totalExpenses = ticketQuantity * 2;
			batchList.value[i].netProfitMoney = batchList.value[i].totalIncome - batchList.value[i].totalExpenses;
			// 中奖数据
			if (batchList.value[i].drawList.length > 0) {
				winBatchList.push({
					id: batchList.value[i].id,
					param: batchList.value[i].param,
					title: batchList.value[i].title,
					drawList: batchList.value[i].drawList,
					maxPrize: batchList.value[i].maxPrize,
					totalIncome: batchList.value[i].totalIncome,
					totalExpenses: batchList.value[i].totalExpenses,
					netProfitMoney: batchList.value[i].netProfitMoney,
				});
			}
		}
		// 中奖汇总统计
		statInfo.value = JSON.parse(JSON.stringify(resetStatInfo));
		prize_info.forEach(item => {
			if (item.value == 0) {
				return;
			}
			statInfo.value['prize' + item.value].prizeMoney = item.money;
		})
		statInfo.value.batchTicketCount = ticketQuantity; // 每方案投注数量
		statInfo.value.totalBatchCount = batchFormData.value.batchQuantity; // 总方案数量
		statInfo.value.totalTicketCount = batchFormData.value.batchQuantity * batchFormData.value
			.ticketQuantity; // 总注数
		statInfo.value.totalExpenses = statInfo.value.totalTicketCount * 2; // 总支出金额
		statInfo.value.winBatchCount = winBatchList.length; // 有中奖方案量
		statInfo.value.noWinBatchCount = statInfo.value.totalBatchCount - winBatchList.length; // 无中奖方案量
		statInfo.value.winBatchCountRate =
			Math.round(100 * winBatchList.length / statInfo.value.totalBatchCount); // 有中奖方案量比例
		statInfo.value.noWinBatchCountRate = 100 - statInfo.value.winBatchCountRate; // 无中奖方案量比例

		let maxPrizeValue = 10;
		winBatchList.forEach(item => {
			if (item.netProfitMoney > 0) {
				statInfo.value.profitBatchCount++; // 盈利方案量
			}
			statInfo.value.totalIncome += item.totalIncome; // 总收入金额
			if (item.maxPrize.value < maxPrizeValue) {
				statInfo.value.maxPrize = {
					...item.maxPrize
				};
				maxPrizeValue = item.maxPrize.value;
			}
			k = 'prize' + item.maxPrize.value;
			statInfo.value[k].list.push(item);
			statInfo.value[k].totalBatchCount++;
			statInfo.value[k].totalTicketCount += item.drawList.filter(v => v.status == item.maxPrize.value)
				.length;
			statInfo.value[k].totalIncome += item.totalIncome;
		})
		statInfo.value.lossBatchCount = statInfo.value.totalBatchCount - statInfo.value.profitBatchCount; // 亏损方案量
		statInfo.value.profitBatchCountRate =
			Math.round(100 * statInfo.value.profitBatchCount / statInfo.value.totalBatchCount); // 盈利方案量比例
		statInfo.value.lossBatchCountRate = 100 - statInfo.value.profitBatchCountRate; // 亏损方案量比例
		statInfo.value.netProfitMoney = statInfo.value.totalIncome - statInfo.value.totalExpenses; // 净收入金额
		// 大数据汇总统计
		let bigStat = getBigStat(),
			k2 = '';
		winBatchList.forEach(item => {
			k = item.param.id;
			bigStat.paramRank[k].winCount++;
			k2 = 'prize' + item.maxPrize.value;
			if (!bigStat.paramRank[k].prizeInfo[k2]) {
				bigStat.paramRank[k].prizeInfo[k2] = {
					title: item.maxPrize.text,
					count: 0
				};
			}
			bigStat.paramRank[k].prizeInfo[k2].count++;
			k = 'prize' + item.maxPrize.value;
			bigStat.prizeRank[k].winCount++;
			k2 = item.param.id;
			if (!bigStat.prizeRank[k].paramInfo[k2]) {
				bigStat.prizeRank[k].paramInfo[k2] = {
					title: item.title,
					count: 0,
				}
			}
			bigStat.prizeRank[k].paramInfo[k2].count++;
		});
		saveBigStat(bigStat);
		winBatchList = null;
	}

	/**
	 * 机选一注
	 */
	const onChooseAuto = (batchIdx, count = 1) => {
		let nums = [],
			n = count == 1 ? count : (count - batchList.value[batchIdx].list.length);
		let filterLevel = parseInt(batchList.value[batchIdx].param.filterLevel);
		let poolType = batchList.value[batchIdx].param.poolType;
		let prevDrawResult = prevDrawInfo.value?.lotteryDrawResult?.trim() || '';
		while (n > 0) {
			nums = dltOrderModel.getRandomNums7(statDrawal, poolType, filterLevel, prevDrawResult, blackNums.value);
			batchList.value[batchIdx].list.push(nums[0].join(' ') + ' ' + nums[1].join(' '));
			n--;
		}
	}

	/**
	 * 优选（在机选号码里面继续机选）
	 */
	const onChooseAutoBetter = (batchIdx) => {
		if (batchList.value[batchIdx].list.length == 0) {
			uni.showToast({
				title: '请先选择机选的号码',
				icon: 'error'
			})
			return;
		}
		let prevDrawResult = prevDrawInfo.value?.lotteryDrawResult?.trim() || '';
		batchList.value[batchIdx].list = dltOrderModel.getBetterNums7(statDrawal, batchList.value[batchIdx].list, '', prevDrawResult, blackNums.value);
	}
</script>

<style>
	:deep(.uni-forms-item) {
		margin-bottom: 4px !important;
	}
</style>